package com.example.aitasks.service;

import com.example.aitasks.config.DefaultProps;
import org.springframework.stereotype.Service;
import java.net.http.*;
import java.net.URI;
import java.time.Duration;
import java.util.regex.*;
import java.util.*;
import java.nio.charset.StandardCharsets;

@Service
public class FetchService {
    private final HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(20))
            .build();
    private final DefaultProps defaults;

    public FetchService(DefaultProps defaults) {
        this.defaults = defaults;
    }

    public String fetchText(String urlOrNull) throws Exception {
        String url = (urlOrNull == null || urlOrNull.isBlank()) ? defaults.getFetchUrl() : urlOrNull;
        HttpRequest req = HttpRequest.newBuilder(URI.create(url))
                .timeout(Duration.ofSeconds(30))
                .header("User-Agent", "ai-task-runner/1.0")
                .GET().build();
        HttpResponse<byte[]> resp = client.send(req, HttpResponse.BodyHandlers.ofByteArray());
        String body = new String(resp.body(), StandardCharsets.UTF_8);

        // naive extraction: if RSS or HTML, pull titles; if JSON, keep fields
        if (body.contains("<rss") || body.contains("<feed")) {
            return extractTitlesFromRss(body);
        } else if (resp.headers().firstValue("content-type").orElse("").contains("json") || body.trim().startsWith("{") || body.trim().startsWith("[")) {
            return body;
        } else {
            return extractTitlesFromHtml(body);
        }
    }

    private String extractTitlesFromRss(String xml) {
        List<String> titles = new ArrayList<>();
        Matcher m = Pattern.compile("<title>(.*?)</title>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(xml);
        while (m.find()) {
            String t = m.group(1).replaceAll("<.*?>", "").trim();
            if (t.length() > 0) titles.add(t);
            if (titles.size() >= 30) break;
        }
        if (!titles.isEmpty()) titles.remove(0); // remove feed title
        return String.join("\n", titles);
    }

    private String extractTitlesFromHtml(String html) {
        List<String> titles = new ArrayList<>();
        Matcher m = Pattern.compile("<a [^>]*>(.*?)</a>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(html);
        while (m.find()) {
            String t = m.group(1).replaceAll("<.*?>", "").trim();
            if (t.length() > 10 && t.length() < 160) titles.add(t);
            if (titles.size() >= 30) break;
        }
        return String.join("\n", titles);
    }
}
